﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace HP.UtilsLib
{
    public class FailsafeTimer
    {
        public delegate void TimeoutEventHander();
        public event TimeoutEventHander FailsafeTimeout;

        private Timer failsafeTimer = null;
        public void Start(int mseconds)
        {
            Debug.WriteLine("lock wait:Start");
            lock (this)
            {
                Debug.WriteLine("lock enter:Start");
                if (failsafeTimer == null)
                {
                    failsafeTimer = new Timer(
                    _ =>
                    {
                        Debug.WriteLine("FailsafeTimer, FailsafeTimeout");
                        FailsafeTimeout?.Invoke();
                        Debug.WriteLine("FailsafeTimer, FailsafeTimeout end");
                    },
                    null,
                    (int)new TimeSpan(0, 0, 0, 0, mseconds).TotalMilliseconds,
                    Timeout.Infinite);
                }
                else
                {
                    failsafeTimer.Change((int)new TimeSpan(0, 0, 0, 0, mseconds).TotalMilliseconds, Timeout.Infinite);
                }
            }
        }

        //public void Reset(int mseconds)
        //{
        //    lock(this)
        //    {
        //        Debug.WriteLine($"FailsafeTimer, Reset to {mseconds}ms.");
        //        if (failsafeTimer != null)
        //        {
        //            failsafeTimer.Change((int)new TimeSpan(0, 0, 0, 0, mseconds).TotalMilliseconds, Timeout.Infinite);
        //        }
        //    }
        //}
        public void Stop()
        {
            Debug.WriteLine("FailsafeTimer lock wait:Stop");
            lock (this)
            {
                Debug.WriteLine("FailsafeTimer lock enter:Stop");
                if (failsafeTimer != null)
                {
                    failsafeTimer.Change(Timeout.Infinite, Timeout.Infinite);
                    failsafeTimer.Dispose();
                    failsafeTimer = null;
                }
            }
        }
    }
}
